/*
 * @Author: wanghao xh-pc@DESKTOP-CVB101Q
 * @Date: 2023-12-19 14:29:50
 * @LastEditors: wanghao xh-pc@DESKTOP-CVB101Q
 * @LastEditTime: 2023-12-22 16:34:07
 * @FilePath: \plm-web\src\utils\xlsx.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%A
 */
import fs from 'file-saver'
import XLSX from 'xlsx'
export function xlsx(json: Array<object>, fields: any, filename = '表格') {
  //导出xlsx

  json.forEach((item: any) => {
    for (const i in item) {
      if (fields[i] !== undefined) {
        item[fields[i]] = item[i]
      }
      delete item[i] //删除原先的对象属性
      // if (fields.hasOwnProperty.call(i)) {
      // 	item[fields[i]] = item[i];
      // }
      // delete item[i]; //删除原先的对象属性
    }
  })
  const sheetName = filename //excel的文件名称
  const wb = XLSX.utils.book_new() //工作簿对象包含一SheetNames数组，以及一个表对象映射表名称到表对象。XLSX.utils.book_new实用函数创建一个新的工作簿对象。
  const ws = XLSX.utils.json_to_sheet(json, { header: Object.values(fields) }) //将JS对象数组转换为工作表。
  wb.SheetNames.push(sheetName)
  wb.Sheets[sheetName] = ws
  const defaultCellStyle = {
    font: { name: 'Verdana', sz: 13, color: 'FF00FF88' },
    fill: { fgColor: { rgb: 'FFFFAA00' } }
  } //设置表格的样式
  const wopts: any = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
    cellStyles: true,
    defaultCellStyle,
    showGridLines: false
  } //写入的样式
  const wbout = XLSX.write(wb, wopts)
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  fs.saveAs(blob, `${filename}.xlsx`)
}

const s2ab = (s: any) => {
  let buf: any
  if (typeof ArrayBuffer !== 'undefined') {
    buf = new ArrayBuffer(s.length)
    const view = new Uint8Array(buf)
    for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
    return buf
  } else {
    buf = Array.from({ length: s.length })
    for (let j = 0; j != s.length; ++j) buf[j] = s.charCodeAt(j) & 0xff
    return buf
  }
}
